<template>
  <div>
    <a-input
      v-model:value="popupValue"
      :placeholder="placeholder"
      :addonBefore="addonBefore"
      :addonAfter="addonAfter"
      :disabled="disabled"
      :bordered="bordered"
      autoComplete="off"
      :size="size"
      allowClear
      @click="showDialog"
      @change="handleChange"
    >
      <template #prefix v-if="prefix">
        <Icon :icon="prefix" />
      </template>
      <template #suffix v-if="suffix">
        <Icon :icon="suffix" />
      </template>
    </a-input>
    <FormItemRest>
      <MultipleSelect
        ref="MultipleSelectRef"
        v-model:multipleDialog="multipleDialog"
        :popupType="popupType"
        :dataSourceOptions="dataSourceOptions"
        :params="params"
        v-model:value="defaultVal"
        v-model:popupValue="popupValue"
        :labelField="labelField"
        :valueField="valueField"
        :datasourceType="datasourceType"
        :dicOptions="dicOptions"
        :apiConfig="apiConfig"
        v-model:selectedDataSource="selectedDataSourceVal"
        :mainKey="mainKey"
        :subTableIndex="index"
        @get-list="getList"
        @submit="handleSubmit"
      />
    </FormItemRest>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch, nextTick, inject } from 'vue';
  import { Form } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';

  import MultipleSelect from './components/MultipleSelect.vue';
  import { camelCaseString } from '/@/utils/event/design';

  const props = defineProps({
    popupType: { type: String },
    value: { type: String },
    labelField: { type: String, default: 'label' },
    valueField: { type: String, default: 'value' },
    placeholder: { type: String },
    addonBefore: { type: String },
    addonAfter: { type: String },
    prefix: { type: String },
    suffix: { type: String },
    disabled: { type: Boolean },
    params: { type: [Array, Object, String, Number] },
    dataSourceOptions: { type: Array },
    dicOptions: { type: Array },
    //数据来源 默认为空  如果不为空 则参数 api
    datasourceType: String,
    apiConfig: { type: Object },
    bordered: {
      type: Boolean,
      default: true,
    },
    mainKey: String,
    index: Number,
    size: String,
  });
  const FormItemRest = Form.ItemRest;
  const formModel = inject<any>('formModel', null);
  const isCustomForm = inject<boolean>('isCustomForm', false);
  const multipleDialog = ref<boolean>(false);
  const popupValue = ref('');
  const defaultVal = ref<string | undefined>('');
  const selectedDataSourceVal = ref<any[]>([]);
  const MultipleSelectRef = ref();
  const dataSourceList = ref<string[]>([]);

  const emit = defineEmits(['update:value', 'change']);

  watch(
    () => props.value,
    () => {
      popupValue.value = '';

      nextTick(async () => {
        await getSubDatasourceList();
        setFormModel();
      });
    },
    {
      immediate: true,
    },
  );

  watch(
    () => props.apiConfig,
    () => {
      nextTick(() => {
        getSubDatasourceList();
      });
    },
  );

  const getList = (list) => {
    dataSourceList.value = list;
  };

  const showDialog = () => {
    multipleDialog.value = true;
  };

  const handleSubmit = (saveValue) => {
    emit('update:value', saveValue);
    emit('change');
  };

  const getSubDatasourceList = async () => {
    let showValueArr: string[] = [];
    await MultipleSelectRef.value.getDatasourceList();

    selectedDataSourceVal.value = [];
    defaultVal.value = props.value;
    const selectedArr = props.value?.split(',');
    dataSourceList.value?.map((item) => {
      selectedArr?.map((selected) => {
        if (item[props.valueField] === selected) {
          selectedDataSourceVal.value?.push(item);
        }
      });
    });

    showValueArr = selectedDataSourceVal.value?.map((item: any) => {
      return item[props.labelField!];
    });

    popupValue.value = showValueArr.length ? showValueArr.join(',') : props.value!;
  };

  const handleChange = (e) => {
    if (!e.target.value) {
      emit('update:value', e.target.value);
      emit('change');
      MultipleSelectRef.value.setFormModel(true);
    }
  };

  const setFormModel = (isNull?) => {
    if (props.popupType === 'associate') {
      let assoConfig = props.datasourceType == 'dic' ? props.dicOptions : [];
      if (!formModel) return;

      assoConfig?.map((item: any) => {
        if (item.bindField) {
          const value = selectedDataSourceVal.value.length
            ? selectedDataSourceVal.value![0][item.name]
            : '';
          if (isCustomForm) {
            if (props.mainKey) {
              formModel[props.mainKey][props.index!][item.bindField!] = isNull ? '' : value;
            } else {
              formModel[item.bindField!] = isNull ? '' : value;
            }
          } else {
            if (props.mainKey) {
              formModel[props.mainKey][props.index!][camelCaseString(item.bindField)!] = isNull
                ? ''
                : value;
            } else {
              formModel[camelCaseString(item.bindField)!] = isNull ? '' : value;
            }
          }
        }
      });
    }
  };
</script>
